package com.pudu.mydemo.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.EditText;

import org.apache.http.conn.util.InetAddressUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class ClientConnectUtils {


	/**
	 * 或取本机的ip地址
	 */
	public static String getlocalip(Context context) {
		WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		String ip = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
				+ (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
		if (ipAddress == 0)
			return "";
		return ip;
	}

	/**
	 * 获取端口所有ip
	 * @return ipaddress
     */
	public static String getLocalHostIp() {
		String ipaddress = "";
		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			// 遍历所用的网络接口
			while (en.hasMoreElements()) {
				NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
				Enumeration<InetAddress> inet = nif.getInetAddresses();
				// 遍历每一个接口绑定的所有ip
				while (inet.hasMoreElements()) {
					InetAddress ip = inet.nextElement();
					if (!ip.isLoopbackAddress()
							&& InetAddressUtils.isIPv4Address(ip
							.getHostAddress())) {
						return ip.getHostAddress();
					}
				}
			}
		}
		catch(SocketException e)
		{
			Log.e("lgq", "获取本地ip地址失败");
			e.printStackTrace();
		}
		return ipaddress;
	}

	/**
	 * dialog
	 */
	public static void customDialog(Context context,String title,final iDialog iDialog){

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title).setIcon(android.R.drawable.ic_dialog_info)
				.setNegativeButton("Cancel", null);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				iDialog.iOnclick();
			}
		});
		builder.show();
	}

	public interface iDialog{
		public void iOnclick();
	}

}
